package com.example.base.job;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.base.app.AppClassService;
import com.example.base.system.SysAppService;
import com.example.base.system.domain.SysApp;
import com.example.base.system.domain.SysJob;
import com.example.base.system.service.SysJobService;
import com.example.base.util.AppClassLoader;
import com.example.base.util.URLClassLoaderUtils;
import com.example.base.utils.ReflectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.net.URLClassLoader;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class LoadJobService {

    @Autowired
    private SysJobService sysJobService;

    @Autowired
    private QuarztUtils quarztUtils;

    @Autowired
    private SysAppService sysAppService;

    @Autowired
    private JobAppMap jobAppMap;

    @Autowired
    private ThreadPoolTaskExecutor asyncServiceExecutor;

    @Autowired
    private AppJobModelService appJobModelService;

    /**
     * 加载app job
     * @param appName
     */
    public void loadJob(String appName){
        asyncServiceExecutor.execute(() -> {
            log.info("开始加载应用 appName: {} job",appName);
            Set<Class<?>> classSet=jobAppMap.getAppJobClass(appName);
            for(Class<?> cls: classSet){
                IJob iJob=(IJob) ReflectUtils.getObjectByClass(cls);
                jobAppMap.add(appName,iJob);
            }
            try {
                List<SysJob> sysJobList=sysJobService.getSysJobAppName(appName);
                List<String> strings=classSet.stream().map(Class::getName).collect(Collectors.toList());
                log.info("任务类列表: "+JSONObject.toJSONString(strings));
                sysJobList.forEach((e)->{
                    log.info("任务类:{}",e.getAppClass());
                    if(strings.contains(e.getAppClass())){
                        JobModel jobModel =appJobModelService.sysJobToJobModel(e);
                        appJobModelService.startJob(jobModel);
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        });
    }
}
